import { ref, ComputedRef, unref, computed, onMounted, watchEffect, watch } from 'vue';
import { isBoolean } from '@/utils/is';
import {PaginationProps} from "naive-ui";
export function useDataSource(
  propsRef: ComputedRef<any>,
  { getPaginationInfo, setPagination, setLoading, tableData },
  emit
) {
  const dataSourceRef = ref<Recordable[]>([]);

  watchEffect(() => {
    tableData.value = unref(dataSourceRef);
  });

  watch(
    () => unref(propsRef).dataSource,
    () => {
      const { dataSource }: any = unref(propsRef);
      dataSource && (dataSourceRef.value = dataSource);
    },
    {
      immediate: true,
    }
  );

  const getRowKey = computed(() => {
    const { rowKey }: any = unref(propsRef);
    return rowKey
      ? rowKey
      : () => {
          return 'key';
        };
  });

  const getDataSourceRef = computed(() => {
    const dataSource = unref(dataSourceRef);
    if (!dataSource || dataSource.length === 0) {
      return unref(dataSourceRef);
    }
    return unref(dataSourceRef);
  });

  async function fetch(opt?) {
    try {
      setLoading(true);
      const { request, pagination }: any = unref(propsRef);
      opt = opt?opt:{
        "filterConditions": [],
        "pageCondition": {
          "pageNum": 1,
          "pageSize": 10
        },
        "sortCondition": {},
        "bizCondition": null
      }
      if (!request) return;
      //组装分页信息
      const pageField = 'pageNum';
      const totalField =  'totalCount';
      const totalFieldPage =  'totalPage';
      const listField = 'data';
      const sizeField = 'size';

      const { page = 1, pageSize = 10 } = unref(getPaginationInfo) as PaginationProps;

      const res = await request(opt);
      console.log(res);
      const resultTotalPage = res[totalFieldPage] || 0;
      const resultTotal = res[totalField] || 0;
      const currentPage = res[pageField];

      // 如果数据异常，需获取正确的页码再次执行
      if (resultTotalPage) {
        if (page > resultTotalPage) {
          setPagination({
            'page': resultTotalPage,
          });
          fetch(opt);
        }
      }
      const resultInfo = res[listField] ? res[listField] : [];
      dataSourceRef.value = resultInfo;
      setPagination({
        'page': currentPage,
        // 'pageCount': resultTotalPage,
        'itemCount':resultTotal
      });
      // if (opt && opt[pageField]) {
      //   setPagination({
      //     'page': opt[pageField] || 1,
      //   });
      // }
      emit('fetch-success', {
        items: unref(resultInfo),
        resultTotal,
      });
    } catch (error) {
      emit('fetch-error', error);
      dataSourceRef.value = [];
    } finally {
      setLoading(false);
    }
  }

  onMounted(() => {
    setTimeout(() => {
      fetch();
    }, 20);
  });

  function setTableData(values) {
    dataSourceRef.value = values;
  }

  function getDataSource(): any[] {
    return getDataSourceRef.value;
  }

  async function reload(opt?) {
    await fetch(opt);
  }

  return {
    fetch,
    getRowKey,
    getDataSourceRef,
    getDataSource,
    setTableData,
    reload,
  };
}
